package com.haumeasoft.snake.os.client.helpers;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import com.haumeasoft.snake.os.client.model.PostParameters;
import com.haumeasoft.snake.os.client.model.SnakeConstants;

import android.os.AsyncTask;
import android.util.Log;


public class PostAsyncTask extends AsyncTask<PostParameters, Void, String> {

	@Override
	protected String doInBackground(PostParameters... postParametersArray) {
		if (postParametersArray == null || postParametersArray.length != 1) {
			throw new IllegalArgumentException("PostAsyncTask can work only with one postParameters object, " 
					+ "no more, no less");
		}
		PostParameters postParameters = postParametersArray[0];
		
		URL url;
		HttpURLConnection conn;
		try {
			// TODO zst 121115: check if this is needed for every call, and if not move it from here
			Authenticator.setDefault(new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(SnakeConstants.USERNAME, 
							SnakeConstants.Password.toCharArray());
				}
			});
			url = new URL(postParameters.getUrl());
			String param = "";
			Map<String, String> parameters = postParameters.getParameters();
			for (Entry<String, String> parameter : parameters.entrySet()) {
				// TODO zst 121115: fix this for multiple parameters
				param = parameter.getKey() + "=" + URLEncoder.encode(parameter.getValue(), "UTF-8"); 
//					"reboot=" + URLEncoder.encode("Reboot", "UTF-8");
			}
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept-Encoding", "identity");
			PrintWriter out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.close();
			String response = "";
			Scanner inStream = new Scanner(conn.getInputStream());
			while (inStream.hasNextLine()) {
				response += (inStream.nextLine());
			}

			Log.d("Response", response);

		} catch (MalformedURLException e) {
			Log.d(SnakeConstants.DEBUG_TAG, "No network connection available.1", e);
		} catch (IOException e) {
			Log.d(SnakeConstants.DEBUG_TAG, "No network connection available.2", e);
		}
		return "Unable to retrieve web page. URL may be invalid.";
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO zst 121115: find a way to show a spining will while post is executing.
	}
}
